package com.yizhang.config;

import com.yizhang.pojo.Configuration;
import com.yizhang.pojo.MappedStatement;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @Author: yi.zhang
 * @CreateTime: 2025-05-27 15:20:19
 * @Description: 解析mapper.xml
 */
@Slf4j
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        // 查询select标签  update|insert|delete同理
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//select");

        String namespace = rootElement.attributeValue("namespace");
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();

            // 保证唯一性  statementId = namespace + '.' + id
            MappedStatement mappedStatement = new MappedStatement();
            String statementId = namespace + "." + id;
            mappedStatement.setStatementId(statementId);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlType("select");

            log.info("statementId: {}", statementId);
            configuration.getMappedStatementMap().put(statementId, mappedStatement);
        }

    }
}
